// 
// 
// 

#include "Relay.h"
#include "parseCMD.hpp"
#define RELAY_PIN	26	

extern QueueHandle_t ParaRelease;
extern QueueHandle_t ParaReturn;

portMUX_TYPE RelayMux = portMUX_INITIALIZER_UNLOCKED;

static void Init_Relay(void);
static void SetRelayState(RelayState state);
static RelayState GetRelayState(void);

void TaskRelay(void* pvParameters)
{
	Init_Relay();
	ParaConfig_t RelayPara;
	RelayPara.type = dRelay;

	while (1)
	{
		if (xQueuePeek(ParaRelease, &RelayPara, 0))
		{
			//taskENTER_CRITICAL(&RelayMux);
			if (RelayPara.type == dRelay)
			{
				xQueueReceive(ParaRelease, &RelayPara, 0);
				if (RelayPara.WR == cR)
				{
					RelayPara.para = (int)GetRelayState();
					xQueueSend(ParaReturn, &RelayPara, 0x10);
				}
				else
				{
					if (RelayPara.para == 0 || RelayPara.para == 1)
					{
						SetRelayState((RelayState)RelayPara.para);
					}
				}
			}
			//taskEXIT_CRITICAL(&RelayMux);
		}
		vTaskDelay(10);
	}
}

static void Init_Relay(void)
{
	pinMode(RELAY_PIN, OUTPUT);
}

static void SetRelayState(RelayState state)
{
	digitalWrite(RELAY_PIN, (uint8_t)state);
}

static RelayState GetRelayState(void)
{
	return (RelayState)digitalRead(RELAY_PIN);
}